package com.taotao.order.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.taotao.common.pojo.TaotaoResult;
import com.taotao.common.util.CookieUtils;
import com.taotao.pojo.TbUser;
import com.taotao.sso.service.UserLoginService;

/**
 * 用户身份认证的拦截器
 * @title LoginInterceptor
 * <p>description</p>
 * <p>company: www.itheima.com</p>
 * @author 天火
 * @version 1.0
 */
public class LoginInterceptor implements HandlerInterceptor {
	
	@Value("${TT_TOKEN_KEY}")
	private String TT_TOKEN_KEY;
	
	@Value("${SSO_URL}")
	private String SSO_URL;
	
	@Autowired
	private UserLoginService userLoginService;

	//返回modelandview后执行
	//异常处理，清理工作
	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	//进入目标方法后，在返回modelandview之前执行
	//公用变量的设置
	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	//进入目标方法前执行
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		//用户身份的认证
		//1.取cookie中的token
		String token = CookieUtils.getCookieValue(request, TT_TOKEN_KEY); 
		//2.判断cookie是否存在
		if(StringUtils.isEmpty(token)) {
			//3.如果不存在，则没有登录，跳转到登录页面；
			//访问localhost:8092/order/order-cart
			response.sendRedirect("http://localhost:8088/page/login?redirect=" + request.getRequestURL().toString());
			return false;
		}
		//4.如果token存在，调用sso的服务查询用户的信息（查看用户是否过期）
		TaotaoResult result = userLoginService.getUserBytoken(token);
		if(result.getStatus()!=200) {
			//5.用户已经过期 ===》重定向到登录页面
			response.sendRedirect(SSO_URL + "/page/login?redirect=" + request.getRequestURL().toString());
			return false;
		}
		
		//6.用户没有过期，（说明已经登录了，放行）
		//设置用户信息到requestzhong
		request.setAttribute("UserInfo", result.getData());
		return true;
	}

}
